//添加授权
var dateTimePicker = require('../../utils/dateTimePicker.js');
//获取应用实例
const app = getApp();
Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        hasAreaNum:app.globalData.hasAreaNum,
        //日期选择
        date: '2018-10-01',
        time: '12:00',
        dateTimeArrayStart: null,
        dateTimeStart: null,
        dateTimeArrayEnd: null,
        dateTimeEnd: null,
        startYear: (new Date).getFullYear(),
        endYear: 2050,
        isEditAdd:'',//判断设置值 修改授权时值为 区域+修改授权 新增授权时 值为新增授权
        userId:'',//修改或新增页面加载和更新数据时 必带参数-用户id
        authorizeId:'',//修改授权时回传id
        authorizeData:'',//判断页面是否为新增  true为新增  false为修改

        tel:'',//手机号
        clientName:'',//当前授权区域
        clientIndex:0,//当前授权区域对应索引
        clientCode:'',//当前区域对应areaCode
        clientArray:{
            clientName:[],
            clientCode:[]
        },//所有区域列表
        authorizeTypeArray: ['单次授权', '永久授权', '临时授权'],//所有授权数据
        authorizeTypeIndex: 0,//当前授权对应code减1
        authorizeType:'单次授权',//当前授权类型
        authorizeStartTime:'',//授权开始时间
        startMillisecond:'',//开始毫秒数
        authorizeEndTime:'',//授权结束时间
        endMillisecond:'',//结束毫秒数
        //授权区域
        checkboxItems: [
            // {name: '客厅', value: '0',areaIds:'1', checked: true},
            // {name: '餐厅', value: '1',areaIds:'2',checked:true},
            // {name: '厨房', value: '2',areaIds:'3'},
            // {name: '主卧', value: '3',areaIds:'4'},
            // {name: '次卧', value: '4',areaIds:'5'},
            // {name: '洗手间', value: '5',areaIds:'6'}
        ],
    },
    bindPickerTypeChange: function(e) {//选择授权类型
        var that = this;
        var index = e.detail.value;
        var authorizeType = that.data.authorizeTypeArray[index];
        this.setData({
            authorizeTypeIndex: index,
            authorizeType:authorizeType
        });
    },
    bindPickerClientChange: function(e) {//选择大区
        var that = this;
        var index = e.detail.value;
        var clientName = that.data.clientArray.clientName[index];
        var clientCode = that.data.clientArray.clientCode[index];

        console.log(clientCode)
        this.setData({
            clientIndex: index,
            clientName:clientName,
            clientCode:clientCode
        });
        //加载对应大区内的小区列表
        that.addLoadArea(clientCode);
    },
    onLoad(options){
        // 调用应用实例的方法获取全局数据
        let app = getApp();
        // toast组件实例
        new app.ToastPannel();
        var that = this;
        //用户信息
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse){
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
        this.setData({
            hasAreaNum:app.globalData.hasAreaNum //设置当前用户所有区域数量
        });
        app.globalData.detailClientCode = options.clientCode; //存储clientCode到全局字段 修改新增完成通过时回跳用户列表时调用
        // 获取完整的年月日 时分秒，以及默认显示的数组
        var objStart = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
        var objEnd = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
        // 精确到分的处理，将数组的秒去掉
        var lastArrayStart = objStart.dateTimeArray.pop();
        var lastTimeStart = objStart.dateTime.pop();
        var lastArrayStart = objStart.dateTimeArray.pop();
        var lastArrayStart = objStart.dateTime.pop();
        var lastArrayEnd = objEnd.dateTimeArray.pop();
        var lastTimeEnd = objEnd.dateTime.pop();
        var lastArrayEndN = objEnd.dateTimeArray.pop();
        var lastTimeEndN = objEnd.dateTime.pop();
        //初始化开始结束时间 如果为新增授权 默认为当前日期时间
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + '年' + month + '月' + strDate + "日 " + date.getHours()+'时';//当前日期
        var currentdateS = new Date(date.getFullYear() + '-' + month + '-' + strDate + " " + date.getHours()+":00").getTime();//当前日期毫秒数
        this.setData({
            dateTimeStart: objStart.dateTime,
            dateTimeArrayStart: objStart.dateTimeArray,
            dateTimeEnd: objEnd.dateTime,
            dateTimeArrayEnd: objEnd.dateTimeArray,
            authorizeStartTime:currentdate,
            authorizeEndTime:currentdate,
            startMillisecond:currentdateS,
            endMillisecond:currentdateS
        });
        that.addLoadClient(); //加载大区 小区域默认数据
        //判断当前页面种类 是新增还是修改授权
        var authorizeData = app.globalData.authorizeData;
        if(options.userId){//判断是否传入userId
            var userId = options.userId;
            this.setData({
                userId:userId,
            });
        }
        var clientCode = options.clientCode;
        this.setData({
            clientCode:clientCode,
            authorizeData:authorizeData
        });
        if (authorizeData==true){//为true时为新增授权
            that.setData({
                isEditAdd:'新增授权',
                authorizeStartTime:currentdate,//新增授权时 默认时间设置为当前时间
                authorizeEndTime:currentdate, //新增授权时 默认时间设置为当前时间
                startMillisecond:currentdateS,
                endMillisecond:currentdateS
            })
        }else{
            that.editLoadData(clientCode,userId);//加载原始数据
            that.setData({
                isEditAdd:'修改授权',
            })
        }


    },
    getUserInfo: function(e) {
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    addLoadClient:function(){//加载大区列表
        var that = this;
        wx.request({//大区列表接口
            url: app.globalData.globalApi+"home/localHouseholdArea?",
            data: {
                isLocation:false
            },
            dataType:"json",
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            header: {
                "token-session":app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function(res){
                const data = res.data.data;
                const length = data.length;
                const clientName = data[0].name;//默认加载第一区域 区域名
                const clientIndex= 0;//默认加载第一区域 区域索引值
                const clientCode= data[0].clientCode;//默认加载第一区域 区域clinetCode
                const clientNameArr= [];//区域名列表
                const clientCodeArr= [];//区域对应clientCode列表
                for(let i=0;i<length;i++){//组装区域数据
                    clientNameArr.push(data[i].name);
                    clientCodeArr.push(data[i].clientCode);
                }
                console.log(clientName+' '+clientIndex+' '+clientCode+' '+clientNameArr+' '+clientCodeArr);
                that.setData({
                    clientName:clientName,
                    clientIndex:clientIndex,
                    clientCode:clientCode,
                    'clientArray.clientName':clientNameArr,
                    'clientArray.clientCode':clientCodeArr
                });
                if (app.globalData.authorizeData==true){//为true时为新增授权
                    that.addLoadArea(clientCode);//加载小区域列表
                }
            }
        });
    },
    addLoadArea:function(clientCode){//加载小区域列表
        var that = this;
        wx.request({//小区域列表接口
            url: app.globalData.globalApi+"home/getUserAccessBisArea/"+clientCode,
            data: {
            },
            dataType:"json",
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            header: {
                "token-session":app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function(res){
                const data = res.data.data;
                const length = data.length;
                const areaData = [];
                console.log(data);
                for(let i=0;i<length;i++){//组装区域数据
                    areaData.push({name:data[i].areaName,value:i,areaIds:data[i].areaCode})
                }
                that.setData({
                    checkboxItems:areaData
                });
            }
        });
    },
    editLoadData:function(clientCode,userId){//修改授权时加载原始数据
        var that = this;
        wx.request({
            url: app.globalData.globalApi + "bisUserAuthorizationRecord/queryBisUserAuthorizationRecordById",//获取设置用户配置接口
            data:{
                clientCode:clientCode,
                userId:userId,
            },
            method: 'get', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType: 'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function (res) {
                console.log(res.data.data);
                var resData = res.data;
                if (resData.success == true && resData.code == 0) {
                    const data = resData.data;
                    const length = data.length;
                    const authData = [];//组装数据预设
                    const authorizeId = data.id;
                    const tel = data.toUserMobile;//手机号
                    const clientName = data.clientName;//区域名
                    const clientCode = data.clientCode;//区域代码
                    const authorizeTypeIndex= data.authorizedType-1;//当前授权对应code
                    const authorizeType=that.data.authorizeTypeArray[authorizeTypeIndex];//当前授权类型
                    const startMillisecond=data.authorizedBeginTime;//开始毫秒数
                    const endMillisecond=data.authorizedEndTime;//结束毫秒数
                    const authorizeStartTime=that.getDateFuc(startMillisecond);//授权开始时间
                    const authorizeEndTime=that.getDateFuc(endMillisecond);//授权结束时间
                    const checkboxItems=[];
                    for (let i = 0; i < data.bisAreaDtoList.length; i++) {//组装区域数据
                        // console.log(data.bisAreaDtoList[i]);
                        checkboxItems.push({name:data.bisAreaDtoList[i].areaName,value:i,areaIds:data.bisAreaDtoList[i].areaCode,checked:data.bisAreaDtoList[i].flagUserArea})
                    }
                    that.setData({
                        authorizeId:authorizeId,
                        tel:tel,
                        clientName:clientName,
                        clientCode:clientCode,
                        authorizeTypeIndex:authorizeTypeIndex,
                        authorizeType:authorizeType,
                        authorizeStartTime:authorizeStartTime,
                        startMillisecond:startMillisecond,
                        authorizeEndTime:authorizeEndTime,
                        endMillisecond:endMillisecond,
                        checkboxItems:checkboxItems
                    });
                    console.log(data.bisAreaDtoList);
                    console.log(endMillisecond);
                    console.log(that.getDateFuc(endMillisecond));

                } else {

                }
            }
        })
    },
    bindChange: function(e){  //失去焦点时 手机号数据写入字段
        var that = this;
        var  tel = e.detail.value;
        this.setData({
            tel:tel
        });
    },
    getDateFuc:function(data){//时间戳转日期函数
        var data = data;
        var unixTimestamp = new Date(data);
        return unixTimestamp.getFullYear() + "年" + (unixTimestamp.getMonth() + 1) + "月" + unixTimestamp.getDate() + "日 " + unixTimestamp.getHours() + "时"
    },
    changeDateTimeStart(e) {
            this.setData({ dateTimeStart: e.detail.value });
            this.changeDateTimeColumnStart(e);
    },
    changeDateTimeEnd(e) {
        this.setData({ dateTimeEnd: e.detail.value });
        this.changeDateTimeColumnEnd(e);
    },
    changeDateTimeColumnStart(e) {
        var arr = this.data.dateTimeStart, dateArr = this.data.dateTimeArrayStart;

        arr[e.detail.column] = e.detail.value;
        dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
        // {{dateTimeArrayStart[0][dateTimeStart[0]]}}-{{dateTimeArrayStart[1][dateTimeStart[1]]}}-{{dateTimeArrayStart[2][dateTimeStart[2]]}} {{dateTimeArrayStart[3][dateTimeStart[3]]}}:{{dateTimeArrayStart[4][dateTimeStart[4]]}}
        var authorizeStartTime = dateArr[0][arr[0]]+"年"+dateArr[1][arr[1]]+"月"+dateArr[2][arr[2]]+"日 "+dateArr[3][arr[3]]+"时";
        var authorizeStartTimeS = new Date(dateArr[0][arr[0]]+"-"+dateArr[1][arr[1]]+"-"+dateArr[2][arr[2]]+" "+dateArr[3][arr[3]]+":00").getTime();//开始时间毫秒取整
        this.setData({
            dateTimeArrayStart: dateArr,
            dateTimeStart: arr,
            authorizeStartTime:authorizeStartTime,
            startMillisecond:authorizeStartTimeS
        });
    },
    changeDateTimeColumnEnd(e) {
        var arr = this.data.dateTimeEnd, dateArr = this.data.dateTimeArrayEnd;

        arr[e.detail.column] = e.detail.value;
        dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
        var authorizeEndTime = dateArr[0][arr[0]]+"年"+dateArr[1][arr[1]]+"月"+dateArr[2][arr[2]]+"日 "+dateArr[3][arr[3]]+"时";
        var authorizeEndTimeS = new Date(dateArr[0][arr[0]]+"-"+dateArr[1][arr[1]]+"-"+dateArr[2][arr[2]]+" "+dateArr[3][arr[3]]+":00").getTime();//结束时间毫秒数取整
        this.setData({
            dateTimeArrayEnd: dateArr,
            dateTimeEnd: arr,
            authorizeEndTime:authorizeEndTime,
            endMillisecond:authorizeEndTimeS
        });
    },
    checkboxChange: function (e) {
        // console.log('checkbox发生change事件，携带value值为：', e.detail.value);
        var checkboxItems = this.data.checkboxItems, values = e.detail.value;
        for (var i = 0, lenI = checkboxItems.length; i < lenI; ++i) {
            checkboxItems[i].checked = false;

            for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
                if(checkboxItems[i].value == values[j]){
                    checkboxItems[i].checked = true;
                    break;
                }
            }
        }
        this.setData({
            checkboxItems: checkboxItems
        });
    },
    //添加或修改授权
    authorizeSaveFuc:function () {
        var that = this;
        // var parameter = {};
        var areaIds='';
        for(var i=0;i<that.data.checkboxItems.length;i++){
            if(that.data.checkboxItems[i].areaIds!=='' && that.data.checkboxItems[i].checked==true){
                areaIds = areaIds+that.data.checkboxItems[i].areaIds+","
            }
        }
        var clientCode  = that.data.clientCode;
        var areaIds  = (areaIds.substring(areaIds.length-1)==',')?areaIds.substring(0,areaIds.length-1):areaIds;
        var toUserMobile  = that.data.tel;
        var authorizedType  = parseInt(that.data.authorizeTypeIndex)+1;//授权类型code为本地授权索引+1
        var createTime  = '';
        var endTime  = '';
        var url = ''; //新增或者修改授权接口地址
        var data = ''; //新增或者修改传入参数
        var phoneReg = !(/^1[34578][0-9]\d{4,8}$/.test(toUserMobile));
        if(authorizedType!==0){//判断是否为永久授权 否则写入起止时间
            createTime  = that.data.startMillisecond;
            endTime  = that.data.endMillisecond
        }
        var curDate = new Date();
        var curS = new Date(curDate.getFullYear() + '-' + (curDate.getMonth()+1) + '-' + curDate.getDate() + " " + curDate.getHours()+":00").getTime();//当前时间
        //存储数据前校验
        if(toUserMobile==''){//验证手机号格式是否正确
            that.show('手机号不能为空!','failed','');
            return false;
        }else if(toUserMobile.length !== 11){
            that.show('手机号号码有误!','failed','');
            return false;
        }else if(phoneReg) {
            that.show('手机号格式不正确!','failed','');
            return false;
        }else if(createTime>=endTime && authorizedType!==2) {
            that.show('授权起止时间设置有误!','failed','');
            return false;
        }if (that.data.endMillisecond && that.data.endMillisecond < curS){
            that.show('授权结束时间设置有误！','failed','');
            return false;
        }else if(areaIds=='') {
            that.show('授权区域不能为空!','failed','');
            return false;
        }
        // console.log(that.checkTelFuc(toUserMobile));

        if(app.globalData.authorizeData==true){//新增或者修改授权接口地址判断
            url = '/bisUserAuthorizationRecord/addBisUserAuthorizationRecord';
            data = {
                clientCode:clientCode,
                areaIds:areaIds,
                toUserMobile:toUserMobile,
                authorizedType:authorizedType,
                createTime:createTime,
                endTime:endTime
            }
        }else{
            url = '/bisUserAuthorizationRecord/updateBisUserAuthorizationRecord';
            data = {
                id:that.data.authorizeId,
                clientCode:clientCode,
                areaIds:areaIds,
                toUserMobile:toUserMobile,
                authorizedType:authorizedType,
                createTime:createTime,
                endTime:endTime
            }
        }
        wx.request({
            url: app.globalData.globalApi + url,
            data:JSON.stringify(data),
            dataType:"json",
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern': app.globalData.experiencePattern// 是否为体验用户
            },
            success: function (res) {
                console.log(res)
                var data = res.data;
                var url = '../settingAuthorizeView/settingAuthorizeView?clientCode='+app.globalData.detailClientCode;
                if (data.success==true && data.code==0){
                    that.show('授权成功','success','',url);//弹出提示信息
                } else{
                    that.show(data.msg,'failed','',url);//弹出提示信息
                }
            }
        });
    },
    // checkTelFuc:function (tel) {
    //     var that = this;
    //     var tel = tel;
    //     // /bisUserAuthorizationRecord/queryBisUserAuthorizationRecordByToUserMobile
    //     wx.request({
    //         url: app.globalData.globalApi + 'bisUserAuthorizationRecord/queryBisUserAuthorizationRecordByToUserMobile',
    //         data: {
    //             toUserMobile:tel
    //         },
    //         dataType: "json",
    //         method: 'get', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    //         header: {
    //             "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
    //             'experience-Pattern': app.globalData.experiencePattern// 是否为体验用户
    //         },
    //         success: function (res) {
    //             var data = res.data;
    //             if (data.code ==0) {//code为0 校验请求成功
    //                 if(data.data !==''&& data.data!==null){//data.data为空代表已授权
    //                     wx.showToast({ //弹出错误信息
    //                         title: '手机号已绑定过授权！',
    //                         icon: "success",
    //                         duration: 1200
    //                     });
    //                 }else{//未授权不给提示
    //                 }
    //             }else{//code大于0 校验接口失败
    //                 wx.showToast({ //弹出错误信息
    //                     title: '校验手机号是否授权失败！',
    //                     icon: "success",
    //                     duration: 1200
    //                 });
    //             }
    //         }
    //     });
    // }


});